import * as db from './db.js' //引入common
// import store from './../store'
//把obj对象里的值覆盖到newobj里面
function deepCopy(newobj, obj) {
	if (typeof obj != 'object') {
		return obj
	}
	for (var attr in obj) {
		var a = {}
		if (newobj[attr]) {
			a = newobj[attr]
		}
		newobj[attr] = deepCopy(a, obj[attr])
	}
	return newobj
}

function isArray(array) {
	return Object.prototype.toString.call(array) === '[object Array]'
}

function urlEncode(obj = {}) {
	const result = []
	for (const key in obj) {
		const item = obj[key]
		if (!item) {
			continue
		}
		if (isArray(item)) {
			item.forEach(val => {
				result.push(key + '=' + val)
			})
		} else {
			result.push(key + '=' + item)
		}
	}
	return result.join('&')
}

function successToShow(msg = '保存成功', callback = function() {}) {
	setTimeout(function() {
		uni.showToast({
			title: msg,
			icon: 'success',
			duration: 2000,
			success() {
				setTimeout(function() {
					callback()
				}, 2000)
			}
		})
	}, 100)
}

//操作失败的提示信息
function errorToShow(msg = '操作失败', callback = function() {}) {
	setTimeout(function() {
		uni.showToast({
			title: msg,
			icon: 'none',
			duration: 1000,
			success() {
				setTimeout(function() {
					callback()
				}, 1000)
			}
		})
	}, 100)
}

//加载显示
function loadToShow(msg = '加载中') {
	uni.showToast({
		title: msg,
		icon: 'loading'
	})
}

//加载隐藏
function loadToHide() {
	uni.hideToast()
}

// 提示框
function modelShow(
	title = '提示',
	content = '确认执行此操作吗?',
	callback = () => {},
	showCancel = true,
	cancelText = '取消',
	confirmText = '确定'
) {
	uni.showModal({
		title: title,
		content: content,
		showCancel: showCancel,
		cancelText: cancelText,
		confirmText: confirmText,
		cancelText: cancelText,
		success: function(res) {
			if (res.confirm) {
				// 用户点击确定操作
				setTimeout(() => {
					callback()
				}, 500)
			} else if (res.cancel) {
				// 用户取消操作
			}
		}
	})
}

//时间戳转时间格式
function timeToDate(date, flag = false, sep = '/', isSec = false) {
	let d = String(date)
	var date = new Date(date * (d.length > 11 ? 1 : 1000)) //如果date为13位不需要乘1000
	var Y = date.getFullYear() + sep
	var M =
		(date.getMonth() + 1 < 10 ?
			'0' + (date.getMonth() + 1) :
			date.getMonth() + 1) + sep
	var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
	var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
	var m =
		(date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes())
	var s = date.getSeconds() < 10 ? ':0' + date.getSeconds() : ':' + date.getSeconds()
	if (flag) {
		return Y + M + D
	} else {
		return Y + M + D + h + m + (isSec ? s : '')
	}
}

//时间戳转时间格式
function timeToDate1(date, flag = false, isSec = false) {
	let d = String(date)
	var date = new Date(date * (d.length > 11 ? 1 : 1000)) //如果date为13位不需要乘1000
	var Y = date.getFullYear() + '年'
	var M =
		(date.getMonth() + 1 < 10 ?
			'0' + (date.getMonth() + 1) :
			date.getMonth() + 1) + '月'
	var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + '日'
	var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
	var m =
		(date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes())
	var s = date.getSeconds() < 10 ? ':0' + date.getSeconds() : ':' + date.getSeconds()
	if (flag) {
		return M + D
	} else {
		return M + D + h + m + (isSec ? s : '')
	}
}

//时间戳转时间格式
function timeToDate2(date, flag = false, isSec = false) {
	let d = String(date)
	var date = new Date(date * (d.length > 11 ? 1 : 1000)) //如果date为13位不需要乘1000
	var Y = date.getFullYear() + '年'
	var M =
		(date.getMonth() + 1 < 10 ?
			'0' + (date.getMonth() + 1) :
			date.getMonth() + 1) + '月'
	var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + '日'
	var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
	var m =
		(date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes())
	var s = date.getSeconds() < 10 ? ':0' + date.getSeconds() : ':' + date.getSeconds()
	return h + m + s
}

function _formatDate(date, fmt) {
	var o = {
		"M+": date.getMonth() + 1, //月份
		"d+": date.getDate(), //日
		"h+": date.getHours(), //小时
		"m+": date.getMinutes(), //分
		"s+": date.getSeconds(), //秒
		"q+": Math.floor((date.getMonth() + 3) / 3), //季度
		"S": date.getMilliseconds() //毫秒
	};
	if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o)
		if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : ((
			"00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
};

function getTimeStringAutoShort2(timestamp, mustIncludeTime) {

	// 当前时间
	var currentDate = new Date();
	// 目标判断时间
	var srcDate = new Date(parseInt(timestamp));

	var currentYear = currentDate.getFullYear();
	var currentMonth = (currentDate.getMonth() + 1);
	var currentDateD = currentDate.getDate();

	var srcYear = srcDate.getFullYear();
	var srcMonth = (srcDate.getMonth() + 1);
	var srcDateD = srcDate.getDate();

	var ret = "";

	// 要额外显示的时间分钟
	var timeExtraStr = (mustIncludeTime ? " " + _formatDate(srcDate, "hh:mm") : "");

	// 当年
	if (currentYear == srcYear) {
		var currentTimestamp = currentDate.getTime();
		var srcTimestamp = timestamp;
		// 相差时间（单位：毫秒）
		var deltaTime = (currentTimestamp - srcTimestamp);

		// 当天（月份和日期一致才是）
		if (currentMonth == srcMonth && currentDateD == srcDateD) {
			// 时间相差60秒以内
			if (deltaTime < 60 * 1000)
				ret = "刚刚";
			// 否则当天其它时间段的，直接显示“时:分”的形式
			else
				ret = _formatDate(srcDate, "hh:mm");
		}
		// 当年 && 当天之外的时间（即昨天及以前的时间）
		else {
			// 昨天（以“现在”的时候为基准-1天）
			var yesterdayDate = new Date();
			yesterdayDate.setDate(yesterdayDate.getDate() - 1);

			// 前天（以“现在”的时候为基准-2天）
			var beforeYesterdayDate = new Date();
			beforeYesterdayDate.setDate(beforeYesterdayDate.getDate() - 2);

			// 用目标日期的“月”和“天”跟上方计算出来的“昨天”进行比较，是最为准确的（如果用时间戳差值
			// 的形式，是不准确的，比如：现在时刻是2019年02月22日1:00、而srcDate是2019年02月21日23:00，
			// 这两者间只相差2小时，直接用“deltaTime/(3600 * 1000)” > 24小时来判断是否昨天，就完全是扯蛋的逻辑了）
			if (srcMonth == (yesterdayDate.getMonth() + 1) && srcDateD == yesterdayDate.getDate())
				ret = "昨天" + timeExtraStr; // -1d
			// “前天”判断逻辑同上
			else if (srcMonth == (beforeYesterdayDate.getMonth() + 1) && srcDateD == beforeYesterdayDate.getDate())
				ret = "前天" + timeExtraStr; // -2d
			else {
				// 跟当前时间相差的小时数
				var deltaHour = (deltaTime / (3600 * 1000));

				// 如果小于或等 7*24小时就显示星期几
				if (deltaHour <= 7 * 24) {
					var weekday = new Array(7);
					weekday[0] = "星期日";
					weekday[1] = "星期一";
					weekday[2] = "星期二";
					weekday[3] = "星期三";
					weekday[4] = "星期四";
					weekday[5] = "星期五";
					weekday[6] = "星期六";

					// 取出当前是星期几
					var weedayDesc = weekday[srcDate.getDay()];
					ret = weedayDesc + timeExtraStr;
				}
				// 否则直接显示完整日期时间
				else
					ret = _formatDate(srcDate, "yyyy/M/d") + timeExtraStr;
			}
		}
	}
	// 往年
	else {
		ret = _formatDate(srcDate, "yyyy/M/d") + timeExtraStr;
	}

	return ret;
};
// 人性化时间格式
function gettime(shorttime) {
	shorttime = shorttime.toString().length < 13 ? shorttime * 1000 : shorttime;
	let now = (new Date()).getTime();
	let cha = (now - parseInt(shorttime)) / 1000;

	if (cha < 43200) {
		// 当天
		return dateFormat(new Date(shorttime.replace(/-/g, "/")), "{A} {t}:{ii}");
	} else if (cha < 518400) {
		// 隔天 显示日期+时间
		return dateFormat(new Date(shorttime.replace(/-/g, "/")), "{Mon}月{DD}日 {A} {t}:{ii}");
	} else {
		// 隔年 显示完整日期+时间
		return dateFormat(new Date(shorttime), "{Y}-{MM}-{DD} {A} {t}:{ii}");
	}
};

function parseNumber(num) {
	return num < 10 ? "0" + num : num;
}

function dateFormat(date, formatStr) {
	let dateObj = {},
		rStr = /\{([^}]+)\}/,
		mons = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'];

	dateObj["Y"] = date.getFullYear();
	dateObj["M"] = date.getMonth() + 1;
	dateObj["MM"] = parseNumber(dateObj["M"]);
	dateObj["Mon"] = mons[dateObj['M'] - 1];
	dateObj["D"] = date.getDate();
	dateObj["DD"] = parseNumber(dateObj["D"]);
	dateObj["h"] = date.getHours();
	dateObj["hh"] = parseNumber(dateObj["h"]);
	dateObj["t"] = dateObj["h"] > 12 ? dateObj["h"] - 12 : dateObj["h"];
	dateObj["tt"] = parseNumber(dateObj["t"]);
	dateObj["A"] = dateObj["h"] > 12 ? '下午' : '上午';
	dateObj["i"] = date.getMinutes();
	dateObj["ii"] = parseNumber(dateObj["i"]);
	dateObj["s"] = date.getSeconds();
	dateObj["ss"] = parseNumber(dateObj["s"]);

	while (rStr.test(formatStr)) {
		formatStr = formatStr.replace(rStr, dateObj[RegExp.$1]);
	}
	return formatStr;
}

function time2date(micro_second) {
	var time = {}
	// 总秒数
	var second = Math.floor(micro_second)
	// 天数
	time.day = PrefixInteger(Math.floor(second / 3600 / 24), 2)
	// 小时
	time.hour = PrefixInteger(Math.floor((second / 3600) % 24), 2)
	// 分钟
	time.minute = PrefixInteger(Math.floor((second / 60) % 60), 2)
	// 秒
	time.second = PrefixInteger(Math.floor(second % 60), 2)

	var newtime = ''
	if (time.day > 0) {
		newtime =
			time.day +
			'天' +
			time.hour +
			'小时' +
			time.minute +
			'分' +
			time.second +
			'秒'
	} else {
		if (time.hour != 0) {
			newtime = time.hour + '小时' + time.minute + '分' + time.second + '秒'
		} else {
			newtime = time.minute + '分' + time.second + '秒'
		}
	}
	return newtime
}

function timeToDateObj(micro_second) {
	var time = {}
	// 总秒数
	var second = Math.floor(micro_second)
	// 天数
	time.day = Math.floor(second / 3600 / 24)
	// 小时
	time.hour = Math.floor((second / 3600) % 24)
	// 分钟
	time.minute = Math.floor((second / 60) % 60)
	// 秒
	time.second = Math.floor(second % 60)

	return time

}

//货币格式化
function formatMoney(number, places, symbol, thousand, decimal) {
	// console.log(number)
	// console.log(places)
	number = number || 0
	places = !isNaN((places = Math.abs(places))) ? places : 2
	symbol = symbol !== undefined ? symbol : '￥'
	thousand = thousand || ','
	decimal = decimal || '.'
	var negative = number < 0 ? '-' : '',
		i = parseInt((number = Math.abs(+number || 0).toFixed(places)), 10) + '',
		j = (j = i.length) > 3 ? j % 3 : 0
	return (
		symbol +
		negative +
		(j ? i.substr(0, j) + thousand : '') +
		i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + thousand) +
		(places ?
			decimal +
			Math.abs(number - i)
			.toFixed(places)
			.slice(2) :
			'')
	)
}
//金额格式化还原
function rmoney(s) {
	return parseFloat(s.replace(/[^\d\.-]/g, ""));
}
//是否排行榜
function isType(str) {
	console.log(str)
	return str ? str.indexOf('rank:') : '';
}

function throttle(fn, context, delay) {
	fn && fn.timeoutId && clearTimeout(fn.timeoutId)
	fn.timeoutId = setTimeout(function() {
		fn.call(context)
	}, delay)
}

// 时间格式化输出，如11:03 25:19 每1s都会调用一次
function dateformat(micro_second) {
	var time = {}
	// 总秒数
	var second = Math.floor(micro_second / 1000) // 天数
	time.day = PrefixInteger(Math.floor(second / 3600 / 24), 2) // 小时
	time.hour = PrefixInteger(Math.floor((second / 3600) % 24), 2) // 分钟
	time.minute = PrefixInteger(Math.floor((second / 60) % 60), 2) // 秒
	time.second = PrefixInteger(Math.floor(second % 60), 2)
	return time
}

//不足位数前面补0
function PrefixInteger(num, length) {
	return (Array(length).join('0') + num).slice(-length)
}

//验证是否是手机号
function isPhoneNumber(str) {
	var myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
	if (!myreg.test(str)) {
		return false
	} else {
		return true
	}
}

/**
 *
 * 对象参数转为url参数
 *
 */
function builderUrlParams(url, data) {
	if (typeof url == 'undefined' || url == null || url == '') {
		return ''
	}
	if (typeof data == 'undefined' || data == null || typeof data != 'object') {
		return ''
	}
	url += url.indexOf('?') != -1 ? '' : '?'
	for (var k in data) {
		url += (url.indexOf('=') != -1 ? '&' : '') + k + '=' + encodeURI(data[k])
	}
	return url
}

/**
 * 使用循环的方式判断一个元素是否存在于一个数组中
 * @param {Object} arr 数组
 * @param {Object} value 元素值
 */
function isInArray(arr, value) {
	for (var i = 0; i < arr.length; i++) {
		if (value === arr[i]) {
			return true
		}
	}
	return false
}
/**
 * 统一跳转
 */
function navigateTo(url) {
	uni.navigateTo({
		url: url,
		animationType: 'pop-in',
		animationDuration: 300
	})
}

/**
 *  关闭当前页面并跳转
 */
function redirectTo(url) {
	uni.redirectTo({
		url: url,
		animationType: 'pop-in',
		animationDuration: 300
	})
}

/**
 * 获取url参数
 *
 * @param {*} name
 * @param {*} [url=window.location.serach]
 * @returns
 */
function getQueryString(name, url) {
	var url = url || window.location.href
	var reg = new RegExp('(^|&|/?)' + name + '=([^&|/?]*)(&|/?|$)', 'i')
	var r = url.substr(1).match(reg)
	if (r != null) {
		return r[2]
	}
	return null
}
/**
 *
 *  判断是否图片
 */
function checkImgType(url) {
	//用文件名name后缀判断文件类型
	if (!/\.(jpg|jpeg|png|GIF|JPG|PNG)$/.test(url)) {
		return false;
	} else {
		return true;
	}
}
/**
 *
 *  判断是否在微信浏览器 true是
 */
function isWeiXinBrowser() {
	// #ifdef H5
	// window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息，这个属性可以用来判断浏览器类型
	let ua = window.navigator.userAgent.toLowerCase()
	// 通过正则表达式匹配ua中是否含有MicroMessenger字符串
	if (ua.match(/MicroMessenger/i) == 'micromessenger') {
		return true
	} else {
		return false
	}
	// #endif

	return false
}

/**
 * 金额相加
 * @param {Object} value1
 * @param {Object} value2
 */
function moneySum(value1, value2) {
	return (parseFloat(value1) + parseFloat(value2)).toFixed(2);
}
/**
 * 金额相减
 * @param {Object} value1
 * @param {Object} value2
 */
function moneySub(value1, value2) {
	let res = (parseFloat(value1) - parseFloat(value2)).toFixed(2);
	return res > 0 ? res : 0;
}


/**
 * 分享URL解压缩
 * @param {Object} url
 */
function shareParameterEncode(url) {
	let urlArray = url.split('-');
	let newUrl = 'type=' + urlArray[0] + '&invite=' + urlArray[1] + '&id=' + urlArray[2] + '&team_id=' + urlArray[3] +
		'&id_type=' + urlArray[4] + '&page_code=' + urlArray[5] + '&group_id=' + urlArray[6];
	return newUrl;
}


/**
 * 分享URL压缩
 * @param {Object} url
 */
function shareParameterDecode(url) {
	var urlArray = url.split('&');
	var allParameter = {
		'type': '',
		'invite': '',
		'id': '',
		'team_id': '',
		'id_type': '',
		'page_code': '',
		'group_id': '',
	};
	for (var i = 0; i < urlArray.length; i++) {
		var parameter = urlArray[i].split('=');
		allParameter[parameter[0]] = parameter[1];
	}
	var newUrl = allParameter.type + '-' + allParameter.invite + '-' + allParameter.id + '-' + allParameter.team_id +
		'-' +
		allParameter.id_type + '-' + allParameter.page_code + '-' + allParameter.group_id;
	return newUrl;
}

function changeNumMoneyToChinese(money) {
	var cnNums = new Array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"); //汉字的数字
	var cnIntRadice = new Array("", "拾", "佰", "仟"); //基本单位
	var cnIntUnits = new Array("", "万", "亿", "兆"); //对应整数部分扩展单位
	var cnDecUnits = new Array("角", "分", "毫", "厘"); //对应小数部分单位
	var cnInteger = "整"; //整数金额时后面跟的字符
	var cnIntLast = "元"; //整型完以后的单位
	var maxNum = 999999999999999.9999; //最大处理的数字
	var IntegerNum; //金额整数部分
	var DecimalNum; //金额小数部分
	var ChineseStr = ""; //输出的中文金额字符串
	var parts; //分离金额后用的数组，预定义
	var Symbol = ""; //正负值标记
	if (money == "") {
		return "";
	}

	money = parseFloat(money);
	if (money >= maxNum) {
		alert('超出最大处理数字');
		return "";
	}
	if (money == 0) {
		ChineseStr = cnNums[0] + cnIntLast + cnInteger;
		return ChineseStr;
	}
	if (money < 0) {
		money = -money;
		Symbol = "负 ";
	}
	money = money.toString(); //转换为字符串
	if (money.indexOf(".") == -1) {
		IntegerNum = money;
		DecimalNum = '';
	} else {
		parts = money.split(".");
		IntegerNum = parts[0];
		DecimalNum = parts[1].substr(0, 4);
	}
	if (parseInt(IntegerNum, 10) > 0) { //获取整型部分转换
		var zeroCount = 0;
		var IntLen = IntegerNum.length;
		for (var i = 0; i < IntLen; i++) {
			var n = IntegerNum.substr(i, 1);
			var p = IntLen - i - 1;
			var q = p / 4;
			var m = p % 4;
			if (n == "0") {
				zeroCount++;
			} else {
				if (zeroCount > 0) {
					ChineseStr += cnNums[0];
				}
				zeroCount = 0; //归零
				ChineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
			}
			if (m == 0 && zeroCount < 4) {
				ChineseStr += cnIntUnits[q];
			}
		}
		ChineseStr += cnIntLast;
		//整型部分处理完毕
	}
	if (DecimalNum != '') { //小数部分
		var decLen = DecimalNum.length;
		for (var i = 0; i < decLen; i++) {
			var n = DecimalNum.substr(i, 1);
			if (n != '0') {
				ChineseStr += cnNums[Number(n)] + cnDecUnits[i];
			}
		}
	}
	if (ChineseStr == '') {
		ChineseStr += cnNums[0] + cnIntLast + cnInteger;
	} else if (DecimalNum == '') {
		ChineseStr += cnInteger;
	}
	ChineseStr = Symbol + ChineseStr;

	return ChineseStr;
}


export {
	deepCopy,
	timeToDate,
	timeToDate1,
	timeToDate2,
	formatMoney,
	/* errorToBack, */
	successToShow,
	throttle,
	errorToShow,
	time2date,
	isPhoneNumber,
	isInArray,
	loadToShow,
	loadToHide,
	navigateTo,
	redirectTo,
	modelShow,
	builderUrlParams,
	isWeiXinBrowser,
	dateformat,
	getQueryString,
	timeToDateObj,
	moneySum,
	moneySub,
	shareParameterEncode,
	shareParameterDecode,
	rmoney,
	getTimeStringAutoShort2,
	urlEncode,
	isType,
	gettime,
	changeNumMoneyToChinese,
	checkImgType
}